package com.sky.controller.user;

import com.sky.constant.StatusConstant;
import com.sky.entity.Category;
import com.sky.result.Result;
import com.sky.service.CategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@Api(tags = "C端分类接口")
@Slf4j
@RequestMapping("/user/category")
@AllArgsConstructor
public class UserCategoryController {


    private CategoryService categoryService;

    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 根据类型查询分类
     * @param type
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("条件查询")
//    @Cacheable(cacheNames = "category_cache", key = "'category'") // category::type 为key的redis
    public Result<List<Category>> list(Integer type){
        String cacheKey = null;
        if (null == type) {
           // 全部都查
            cacheKey = "category_cache::category:type:all";
        }else {
            cacheKey = "category_cache::category:type"+type;
        }

        List<Category> cacheData = (List<Category>) redisTemplate.opsForValue().get(cacheKey);
        if(null != cacheData && cacheData.size()>0) {
            return Result.success(cacheData);
        }

        List<Category> list = categoryService.list(type);
        List<Category> filterList = list.stream().filter(item -> Objects.equals(item.getStatus(), StatusConstant.ENABLE)).collect(Collectors.toList());
        // 查询到的数据存入缓存
        redisTemplate.opsForValue().set(cacheKey, filterList);

        return Result.success(filterList);
    }

}
